<html>
<head>
<script src="jquery.js"></script>
<script src="md5.js"></script>
<script src="rtm.js"></script>

<script>

var pollInterval = 1000 * 60 * 5; // 5 minutes
var scheduleTime = 1000 * 10; // 10 seconds
var t; // timer id

function setBadgeText(text) {
	chrome.browserAction.setBadgeBackgroundColor({color:[19, 92, 190, 255]});
	chrome.browserAction.setBadgeText({text:text});
}

function init() {
	startRequest();
}

function scheduleRequest() {
	console.log('scheduling request');
	stopRequest();
	t = window.setTimeout(startRequest, scheduleTime);
}

function startRequest() {
	
	if (localStorage['badge'] == 'true') {
		var filter = 'dueBefore:tomorrow';
		if (localStorage['style'] == 'custom') {
			if (localStorage['customFilter'] != 'undefined') {
				filter = localStorage['customFilter'];
			}
		}
		else if (localStorage['style'] == 'all'){
			filter = '';
		}

		rtmIncompleteTasks(
			filter, 
			function(numTasks) {
				if (numTasks != 0)
					setBadgeText(numTasks+'');
				else
					setBadgeText('');
			},
			function(rsp) {
				// error, fail silently
				setBadgeText('');
			}
		);
	}
	else {
		setBadgeText('');
	}
	
	t = window.setTimeout(startRequest, pollInterval);
}

function stopRequest() {
	window.clearTimeout(t);
}

</script>
</head>
<body onload='init()'>
</body>
</html>